//
//  AppDelegate.m
//  HaoDeCaiFu
//
//  Created by 郑开宏 on 2017/10/27.
//  Copyright © 2017年 郑开宏. All rights reserved.
//

#import "AppDelegate.h"
#import "HDCFTabbarController.h"
#import "ViewController.h"
#import "QCStartAnimationtViewController.h"
#import "IQKeyboardManager.h"
#import "AFNetworking.h"
#import <CommonCrypto/CommonDigest.h>
#define KSelfUrl @"http://jx.chinahonden.xyz:15504/"
@interface AppDelegate ()<UIAlertViewDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    [self.window makeKeyAndVisible];
//    self.window.backgroundColor = [UIColor whiteColor];
    
    HDCFTabbarController * vc = [[HDCFTabbarController alloc] init];
    self.window.rootViewController = vc;
    [self chooseRootController:vc];

    
    //设置为文字
    [IQKeyboardManager sharedManager].toolbarDoneBarButtonItemText = @"完成";
    [IQKeyboardManager sharedManager].enable = YES;//键盘
    //设置字体颜色
    [IQKeyboardManager sharedManager].shouldToolbarUsesTextFieldTintColor = NO;
    [IQKeyboardManager sharedManager].toolbarTintColor = ZKcolor(184, 27, 36);
    
    return YES;
}

- (void)chooseRootController:(UIViewController *)launchVC
{
    NSString *key = @"CFBundleVersion";
    
    // 取出沙盒中存储的上次使用软件的版本号
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *lastVersion = [defaults stringForKey:key];
    
    // 获得当前软件的版本号
    NSString *currentVersion = [NSBundle mainBundle].infoDictionary[key];
    if ([currentVersion isEqualToString:lastVersion]) {
        // 显示状态栏
        [UIApplication sharedApplication].statusBarHidden = NO;
        
        self.window.rootViewController = launchVC;
    }
    else {
        // 新版本
        QCStartAnimationtViewController *newFeature = [[QCStartAnimationtViewController alloc] init];
        newFeature.appDelegateView = launchVC;
        self.window.rootViewController = newFeature;
        //存储新版本
        [defaults setObject:currentVersion forKey:key];
        [defaults synchronize];
    }
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (NSString *)md5:(NSString *)string{
    const char *cStr = [string UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), digest);
    
    NSMutableString *result = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [result appendFormat:@"%02X", digest[i]];
    }
    
    return result;
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
    if (md5Token) {
        NSDate *senddate = [NSDate date];
        NSString *date2 = [NSString stringWithFormat:@"%ld", (long)[senddate timeIntervalSince1970]];
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[@"userId"] = kAcount;
        dict[@"deviceName"] = @"ios";
        dict[@"timeStamp"] = date2;
        NSString *longStr = [NSString stringWithFormat:@"%@%@", date2, md5Token];
        dict[@"exchangeToken"] = [self md5:longStr];
        [self sendSelfPostTwoRequestWithURL:@"api/Auth/ExchangeToken" WithParamets:nil WithParamet:dict success:^(id result) {
            if ([result[@"code"] isEqual:@1]) {
                NSDictionary *dataDict = result[@"result"];
                NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
                if (dataDict[@"Token"]) {
                    [user setValue:dataDict[@"Token"] forKey:@"Token"];
                }
//                NSLog(@"%@",dataDict[@"LoginName"]);
//                if (dataDict[@"LoginName"]&&![dataDict[@"LoginName"] isEqual:[NSNull null]]&&![dataDict[@"LoginName"] isEqualToString:@"<null>"]) {
//                    [user setValue:dataDict[@"LoginName"] forKey:@"accountName"];
//                }
//                NSNumber *openStatus = dataDict[@"HoldingCode"];
//                if (openStatus &&![openStatus isEqual:[NSNull null]]) {
//                    [user setValue:openStatus.stringValue forKey:@"OpenStatue"];
//
//                }
                NSString *exToken = [NSString stringWithFormat:@"%@%@", md5Token, dataDict[@"Token"]];
                NSString *md5Str = [self md5:exToken];
                [user setValue:md5Str forKey:@"exToken"];
                [user synchronize];
            }
        } failure:^(NSError *errer) {
            
        }];
    }
}
- (void)sendSelfPostTwoRequestWithURL:(NSString *)url WithParamets:(NSString *)jsonString WithParamet:(NSDictionary *)dict success:(void(^)(id result))success failure:(void(^)(NSError *errer))failure {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 15.0;
    NSString *u = [NSString stringWithFormat:@"%@%@?", KSelfUrl, url];
    NSArray *keys = dict.allKeys;
    NSString *str;
    for (int i = 0; i < keys.count; i++) {
        NSString *key = keys[i];
        if (i == 0) {
            str = [NSString stringWithFormat:@"%@=%@&", key, dict[key]];
        }else{
            str = [NSString stringWithFormat:@"%@%@=%@&",str, key, dict[key]];
        }
    }
    NSString *urlt = [NSString stringWithFormat:@"%@%@", u, [str substringToIndex:str.length - 1]];
    NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:urlt parameters:nil error:nil];
    [req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (!error) {
            success(responseObject);
        } else {
            failure(error);
        }
        
    }] resume];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
//    [HttpRequest sendSelfGetRequestWithURL:@"file/VersionInfo.json" WithParamets:nil success:^(id result) {
//        NSDictionary *dataDict = result[@"IOS"];
//        //先获取当前工程项目版本号
//        NSDictionary *infoDic=[[NSBundle mainBundle] infoDictionary];
//        NSString *currentVersion = infoDic[@"CFBundleShortVersionString"];
//        if ([currentVersion isEqualToString:dataDict[@"Remark"]]) {
//
//        }else {
//            if ([dataDict[@"Required"] integerValue] == 1) {//强制更新
//                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"有新版本需要更新" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:@"更新", nil];
//                alert.delegate = self;
//                alert.tag = 100;
//                [alert show];
//            }else {
//                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"有新版本需要更新" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"更新", nil];
//                alert.delegate = self;
//                alert.tag = 200;
//                [alert show];
//            }
//        }
//    } failure:^(NSError *errer) {
//        [SVProgressHUD showInfoWithStatus:@"服务器错误"];
//        [SVProgressHUD dismissWithDelay:1.0];
//    }];
}

//alertView 代理
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.tag == 100) {
        NSURL *url3 = [NSURL URLWithString:@"https://itunes.apple.com/cn/app/xxx/idxxx?l=en&mt=x"];
        [[UIApplication sharedApplication] openURL:url3];
    }else {
        if (buttonIndex == 1) {
            NSURL *url3 = [NSURL URLWithString:@"https://itunes.apple.com/cn/app/xxx/idxxx?l=en&mt=x"];
            [[UIApplication sharedApplication] openURL:url3];
        }
    }
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
